<template>
  <div class="taskVerifyDetail h100">
    <template v-if="auditItemInfo.activeVerifyItemId">
      <div class="taskVerifyDetailTop">
        <div style="position: relative">
          <full-parent-dom-with-dask :loading="loadingDetail"></full-parent-dom-with-dask>
          <!-- 审核对象的操作信息、基本信息、(升级车辆|测试结果|车型服务) -->
          <component
            :is="
              auditObjectConfig[this.auditItemInfo.relType]
                ? auditObjectConfig[this.auditItemInfo.relType].compName
                : null
            "
            :info="info"
            :linkedInfo="linkedInfo"
            @clickdetail="doAction"
          >
          </component>
        </div>
        <!-- 审核流程 -->
        <div class="baseInfo boxItem">
          <h4 class="withVerticleLineT4 title14">{{ $t('auditProcess') }}</h4>
          <div class="descBox">
            <lookup-verify-detail
              ref="lookupVerifyDetailRef"
              :verify-id="verifyId"
              :rel-id="linkedId"
              :rel-type="relType"
              :items="info.items"
            ></lookup-verify-detail>
          </div>
        </div>
        <!-- 审核意见 -->
        <div class="baseInfo boxItem" v-if="needVerify">
          <h4 class="withVerticleLineT4 title14">{{ $t('reviewComments') }}</h4>
          <div class="descBox">
            <edit-verify-info ref="editVerifyInfoRef" :show-title="false"></edit-verify-info>
          </div>
        </div>
      </div>
      <div class="taskVerifyDetailFooter">
        <div v-if="needVerify">
          <auth-button
            :auth="managePerms.audit.edit"
            @click="adopt"
            :loading="savingAgreen"
            :disabled="savingReject"
            style="margin-right: 24px"
          >{{ $t('agree') }}</auth-button
          >
          <auth-button
            type="info"
            :auth="managePerms.audit.edit"
            @click="reject"
            :loading="savingReject"
            :disabled="savingAgreen"
            style="margin-right: 24px"
          >{{ $t('reject') }}</auth-button
          >
        </div>
        <p v-else>
          {{ $t('auditResult') }}：
          <span :class="{ reject: info.status === 3, ok: info.status === 4 }">{{
            auditStatusDictCodeObj[info.status]
          }}</span>
        </p>
      </div>
    </template>
    <span v-else style="text-align: center;padding-top: 20px;">{{ $t('noData') }}</span>
  </div>
</template>
<script>
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import LookupVerifyDetail from '@/views/components/AuditProcess/displayTbList.vue'
import EditVerifyInfo from './EditVerifyInfo'
import TaskVerifyDetailService from './TaskVerifyDetailService'
import TaskVerifyDetailStrategy from './TaskVerifyDetailStrategy'
import TaskVerifyDetailTask from './TaskVerifyDetailTask'
import verifyApi from '@/api/modules/system/verify'
import FullParentDomWithDask from '@/components/LoadDataSpin/FullParentDomWithDask.vue'
import taskApi from '@/api/modules/task'
import AuthButton from '@/components/AuthButton'
import { managePerms } from '@/config/permission/index'
import serviceConfigApi from '@/api/modules/software/serviceConfig'
const initInfo = {
  // 当前审核流程
  items: [],
  // 当前审核人id
  currentItemUserId: ''
}
const initInfoData = {
  totalVehicle: '-',
  successVehicle: '-',
  notStartVehicle: '-',
  notCompleteVehicle: '-',
  failVehicle: '-',
  runningVehicle: '-',
  pausedVehicle: '-'
}
export default {
  components: {
    TableEllipsis,
    LookupVerifyDetail,
    EditVerifyInfo,
    FullParentDomWithDask,
    AuthButton,
    TaskVerifyDetailService,
    TaskVerifyDetailStrategy,
    TaskVerifyDetailTask
  },
  props: {
    verifyId: {
      type: [String, Number],
      default: ''
    },
    linkedId: {
      type: [String, Number],
      default: ''
    },
    relType: {
      type: [String, Number],
      default: ''
    },
    auditItemInfo: {
      type: Object,
      default () {
        return {
          activeVerifyItemId: '',
          activeLinkId: '',
          relType: '',
          linkedExtId: ''
        }
      }
    },
    // 审核项是策略时，策略发布时所选择的测试任务id
    linkedExtId: {
      type: String,
      default: ''
    },
    nowTime: {
      type: Number,
      default: 0
    }
  },
  computed: {
    taskTypeObj () {
      return this.$store.getters.getTaskDictCodeObj('taskType')
    },
    auditStatusDictCodeObj () {
      return this.$store.getters.getDictCodeObj('auditStatusDictCode')
    },
    // 本人是否已处理过
    needVerify () {
      return this.info.currentItemUserId === this.$store.getters.userId && this.info.status === 1
    },
    // 审核项是否为任务
    isTask () {
      return this.auditItemInfo.relType === 'FOTA_NORMAL_TASK'
    },
    // 审核项是否为策略
    isStrategy () {
      return this.auditItemInfo.relType === 'FOTA_UPGRADE_STRATEGY'
    },
    // 审核项是否为服务
    isService () {
      return this.auditItemInfo.relType === 'SOTA_MODEL_SERVICE'
    }
  },
  data () {
    return {
      managePerms,
      info: { ...initInfo },
      loadingDetail: false,
      linkedInfo: {},
      strategyId: '',
      savingAgreen: false,
      savingReject: false,
      strategyType: 'Fota',
      // 审核对象配置(任务,策略,服务)
      auditObjectConfig: {
        FOTA_NORMAL_TASK: {
          compName: 'TaskVerifyDetailTask'
        },
        FOTA_UPGRADE_STRATEGY: {
          compName: 'TaskVerifyDetailStrategy'
        },
        SOTA_MODEL_SERVICE: {
          compName: 'TaskVerifyDetailService'
        }
      }
    }
  },
  watch: {
    nowTime: {
      handler () {
        this.getDetailData()
      },
      immediate: true
    }
  },
  methods: {
    // 获取当前项的详情及关联的要审核对象的详情
    getDetailData () {
      this.loadingDetail = true
      const methods = [this.getActiveVerifyDetail()]
      if (this.isTask) {
        methods.push(this.getLinkedTaskDetail())
      } else if (this.isStrategy) {
        methods.push(this.getLinkedTeskTaskTjDetail())
      } else if (this.isService) {
        methods.push(this.getLinkedVehicleServiceData())
      }
      Promise.all(methods)
        .finally(() => {
          this.loadingDetail = false
        })
    },
    // 获取详情数据
    getActiveVerifyDetail () {
      return new Promise((resolve, reject) => {
        this.info = { ...initInfo }
        if (!this.auditItemInfo.activeVerifyItemId || !this.auditItemInfo.relType) {
          console.log('getActiveVerifyDetail0')
          resolve(true)
          return
        }
        console.log('getActiveVerifyDetail')
        const params = { id: this.auditItemInfo.activeVerifyItemId, relType: this.auditItemInfo.relType }
        verifyApi
          .getVerifyInfoDetail(params)
          .then((res) => {
            this.info = res.data ? res.data : {}
            resolve(res.data)
          }).catch(err => {
            reject(err)
          })
          .finally(() => {})
      })
    },
    // 获取相关联任务详情
    getLinkedTaskDetail () {
      return new Promise((resolve, reject) => {
        this.linkedInfo = {}
        if (!this.auditItemInfo.activeLinkId) {
          resolve(true)
          return
        }
        taskApi
          .getTaskInfor({ id: this.auditItemInfo.activeLinkId })
          .then((res) => {
            this.linkedInfo = res.data ? res.data : {}
            resolve(res.data)
          }).catch(err => {
            reject(err)
          })
          .finally(() => {})
      })
    },
    // 获取相关联测试任务的测试结果
    getLinkedTeskTaskTjDetail () {
      return new Promise((resolve, reject) => {
        this.linkedInfo = {}
        if (!this.auditItemInfo.linkedExtId) {
          resolve(true)
          return
        }
        taskApi
          .getUpgradeStatisticsReport({ taskIds: [this.auditItemInfo.linkedExtId] })
          .then((res) => {
            if (!res.data) {
              return
            }
            const data = this.setUndefinedVal(res.data)
            this.linkedInfo = {
              totalVehicle: data.totalVehicle,
              successVehicle: data.successVehicle,
              notStartVehicle: data.notStartVehicle,
              notCompleteVehicle: data.notCompleteVehicle,
              failVehicle: data.failVehicle,
              runningVehicle: data.runningVehicle,
              pausedVehicle: data.pausedVehicle
            }
            resolve(res.data)
          })
          .finally(() => {})
          .catch((err) => {
            reject(err)
          })
      })
    },
    //   获取审核项是服务对应的车型服务数据
    getLinkedVehicleServiceData () {
      return new Promise((resolve, reject) => {
        this.linkedInfo = {}
        if (!this.auditItemInfo.activeLinkId) {
          resolve(true)
          return
        }
        serviceConfigApi
          .getAuditedServiceVehicleData(this.auditItemInfo.activeLinkId)
          .then((res) => {
            const { data } = res
            this.linkedInfo = {
              modelCode: data.modelCode,
              modelName: data.modelName,
              trimLevel: data.trimLevel,
              services: data.services
            }
            resolve(res.data)
          })
          .finally(() => {})
          .catch((err) => {
            reject(err)
          })
      })
    },
    setUndefinedVal (data) {
      Object.keys(initInfoData).forEach((key) => {
        if (typeof data[key] === 'undefined') {
          // eslint-disable-next-line no-param-reassign
          data[key] = '-'
        }
      })
      return data
    },
    // 通过
    adopt () {
      if (!this.checkVerify()) {
        return
      }
      this.$refs.editVerifyInfoRef.getFormData().then((data) => {
        // eslint-disable-next-line no-param-reassign
        data.actionItemId = this.info.currentItemId
        // eslint-disable-next-line no-param-reassign
        data.status = 3
        this.saveEditVerifyInfoData(data)
      })
    },
    // 驳回
    reject () {
      if (!this.checkVerify()) {
        return
      }
      this.$refs.editVerifyInfoRef.getFormData().then((data) => {
        // eslint-disable-next-line no-param-reassign
        data.actionItemId = this.info.currentItemId
        // eslint-disable-next-line no-param-reassign
        data.status = 2
        this.saveEditVerifyInfoData(data)
      })
    },
    checkVerify () {
      if (!this.info.currentItemId) {
        console.error('缺少currentItemId参数!')
        return false
      }
      return true
    },
    // 保存通过审核数据
    saveEditVerifyInfoData (data) {
      const method = 'editVerifyStateData'
      const savingKey = data.status === 3 ? 'savingAgreen' : 'savingReject'
      this[savingKey] = true
      this.$store
        .dispatch(method, data)
        .then(() => {
          this.$message.success(this.$t('successfullyOperation'))
          this.$refs.editVerifyInfoRef.resetFormData()
          // 更新页面
          this.getActiveVerifyDetail().then(() => {
            console.log(this.info.status, 'status')
            this.$emit('saved', { verifyId: this.auditItemInfo.activeVerifyItemId, status: this.info.status })
          })
          this.$refs.lookupVerifyDetailRef.loadPageData()
        })
        .catch((err) => {
          console.error(err)
        })
        .finally(() => {
          this[savingKey] = false
        })
    },
    doAction (data) {
      this.$emit('clickdetail', data)
    }
  }
}
</script>
<style lang="less">
.taskVerifyDetail {
  display: flex;
  flex-direction: column;

  .taskVerifyDetailTop {
    position: relative;
    flex: 1;
    overflow: auto;
    padding: 15px 24px;
    min-width: 800px;
  }

  .bb {
    border-bottom: 1px solid @borderColor;
  }

  .boxItem {
    padding: 15px 0;
  }

  .title14 {
    margin-bottom: 10px;
  }

  .descBox {
    display: flex;

    .descCol1 {
      width: 30%;
    }

    .descCol2 {
      width: 40%;
    }

    .descCol3 {
      width: 30%;
    }
    .descColHalf {
      width: 50%;
    }
    .descColFull {
      width: 100%;
      .descValue {
        line-height: 1.5em;
        text-align: justify;
      }
    }
  }

  .descItem {
    padding: 8px 0;
    font-size: 0.9em;
    display: flex;
  }

  .descTitle {
    font-weight: bold;
    flex: 120px 0 0;
  }

  .descValue {
    flex: 1 0 0;
    font-size: 1em;
  }

  .taskVerifyDetailFooter {
    padding: 15px 24px;
    flex: none;
    border-top: 1px solid @borderColor;

    .ok {
      color: #46d5a2;
      font-weight: bold;
    }

    .reject {
      color: #fe8b67;
      font-weight: bold;
    }
  }
}
</style>
